<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <button class="btn1"><h1>节流打印1</h1></button>
        <button class="btn2"><h1>防抖打印2</h1></button>
    </body>
    <script>
        function clg() {
            console.log(1);
        }
        // 节流（点击后多次点击在一段时间内只会执行一次）
        function throttle(fn, time1) {
            //return的这个函数才是真正的事件函数
            let lastTime = 0;
            return function (e) {
                let nowTime = Date.now();
                if (nowTime - lastTime < time1) {
                    return;
                }
                lastTime = nowTime;

                //调用核心代码
                fn.call(this, e);
            };
        }
        const btn1 = document.querySelector(".btn1");
        const time = 500;
        const lastTime = 0;

        btn1.onclick = throttle(clg, time);

        // 防抖（点击后等一段时间不再点击，则会执行，连续点击不执行）

        function debounce(fn, time1) {
            let timer = null
            return function(e) {
                clearTimeout(timer)
                timer = setTimeout(()=>{
                    fn.call(this, e)
                }, time1)
            }
        }
        const btn2 = document.querySelector(".btn2");
        btn2.onclick = debounce(clg, time)

    </script>
</html>
